package com.bwie.redkids.utils;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.bwie.redkids.base.FavoriteSQLITE;
import com.bwie.redkids.bean.Favorites;

public class FavoriteDBUtils {

	private SQLiteDatabase db;

	public void openSQLite(Context context) {
		FavoriteSQLITE sqlite = new FavoriteSQLITE(context);
		db = sqlite.getReadableDatabase();
	}

	public void insert(Favorites fs) {
		db.execSQL("insert into favorite(name_id,name,state) values("
				+ fs.getName_id() + ",'" + fs.getName() + "',1)");
	}

	public void update(int name_id, Favorites fs) {
		int i = query(name_id);
		if (i == 1) {
			db.execSQL("update favorite set state=0 where name_id=" + name_id);
		} else {
			Cursor c = db.rawQuery(
					"select state from favorite where name_id=?",
					new String[] { name_id + "" });
			if (!c.moveToFirst()) {
				insert(fs);
			} else {
				db.execSQL("update favorite set state=1 where name_id="
						+ name_id);
			}

		}
	}

	/**
	 * 将已收藏状态的商品状态改为为收藏
	 * 
	 * @param name_id
	 *            已收藏商品的id
	 * @author 李杰 DBUtils void
	 */
	public void update(int name_id) {

		db.execSQL("update favorite set state=0 where name_id=" + name_id);
	}

	public int query(int name_id) {
		Cursor c = db.rawQuery("select state from favorite where name_id=?",
				new String[] { name_id + "" });
		if (c.moveToFirst()) {
			int i = c.getInt(c.getColumnIndex("state"));
			return i;
		}
		return 0;

	}

	/**
	 * 查询数据库中所有的已收藏状态的数据
	 * 
	 * @return
	 * @author 李杰 DBUtils ArrayList<Favorites>
	 */
	public ArrayList<Favorites> query() {
		ArrayList<Favorites> lt = new ArrayList<Favorites>();
		Cursor c = db.rawQuery("select * from favorite where state=1", null);
		while (c.moveToNext()) {
			int name_id = c.getInt(c.getColumnIndex("name_id"));
			int state = c.getInt(c.getColumnIndex("state"));
			String name = c.getString(c.getColumnIndex("name"));
			Favorites favorites = new Favorites(name_id, name, state);
			lt.add(favorites);
		}
		return lt;

	}

	public void closeSQLite() {
		db.close();
	}
}
